package com.fairytask.ui
{
	import com.adobe.utils.StringUtil;
	import com.fairytask.engine.GameStage;
	import com.fairytask.engine.components.button.Button;
	import com.fairytask.engine.components.checkBox.CheckBox;
	import com.fairytask.engine.components.clip.Clip;
	import com.fairytask.engine.components.text.Input;
	import com.fairytask.engine.components.text.Label;
	import com.fairytask.engine.components.tree.Tree;
	import com.fairytask.engine.components.tree.TreeEvent;
	import com.fairytask.engine.define.ResConfig;
	import com.fairytask.managers.ResManager;
	import com.fairytask.resource.StaticIni;
	import com.fairytask.ui.base.FrameUI;
	
	import flash.display.DisplayObject;
	import flash.display.MovieClip;
	import flash.display.Shape;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.geom.Point;
	
	/**
	 * 小地图UI 
	 * @author xujh
	 * 
	 */
	public class MiniMapUI extends FrameUI
	{
		public static var _self:MiniMapUI;
//		public var pageTab	:TabBar;
		//选项
		public var allCkb		:CheckBox;
		public var shopCkb		:CheckBox;
		public var normalCkb	:CheckBox;
		public var allLab		:Label;
		public var shopLab		:Label;
		public var normalLab	:Label;
		
		public var bg_mc2	:MovieClip;
		public var bg_mc3	:MovieClip;
		
		public var findbtn		:Button;	//搜寻按钮
		public var findinput	:Input;	//查找输入框
		public var npcTree		:Tree;
		public var findTree		:Tree;
		
		public var mapClip		:Clip;
		public var title		:String;
		//小地图鼠标跟随坐标
		private var mousePosLab	:Label	=	new Label;
		
		private var _clipFrame	:Shape;//地图边框(黄色)
//		private var _bindArr	:Array	=	[];
		
		private var _scale		:int;
		private var _mapPoint	:Point;
		private var _movemc		:Clip;
		private var _startpoint	:Point
		//用于存储npc数据
		private var _npcListArr		:Array	=	[];
		//显示搜索结果
		private var _showFind	:Boolean	=	false;
		
		private var drowline	:Sprite=new Sprite();
		private var _endPoint	:Point=new Point();
		private var _business	:Sprite=new Sprite();	//商业
//		private var _transmit	:Sprite=new Sprite();	//传送
		private var _common		:Sprite=new Sprite();	//普通
//		private var _task		:Sprite=new Sprite();	//任务
//		private var _activity	:Sprite=new Sprite();	//活动
//		private var _obtain		:Sprite=new Sprite();	//领双
//		private var _panelArr	:Array=[];
		//npcTree父分类序号
		private const SHOPNPC	:int	=	0;	//商业
		private const NORMALNPC	:int	=	1;	//普通
		
		private var _initMap	:Boolean	=	false;
		
		public static function getInstance():MiniMapUI
		{
			if(_self == null)
			{
				_self	=	new MiniMapUI;
			}
			return _self;
		}
		
		public function MiniMapUI(popUI:Boolean=true)
		{
			super(popUI);
			_business.mouseChildren	=	false;
			_business.mouseEnabled=false;
			
			_common.mouseChildren    =   false;
			_common.mouseEnabled    =   false;
			
			
			mapClip=new Clip(false,onLoaded);
			
			_movemc=new Clip();
			_movemc.source = ResConfig.pngResPath + "resUI/onMap.png";
			//添加npc列表父节点
			npcTree.addItem(StaticIni.getSwfLangStr("1000000617")); 
			npcTree.addItem(StaticIni.getSwfLangStr("1000000618")); 
			
			initEvent();
		}
		
		/**
		 *监听 
		 * 
		 */		
		private function initEvent():void
		{
			//npc列表
			npcTree.addEventListener(TreeEvent.DOUBLE_CLICK_ITEM,onNpctreeEvent);
			findTree.addEventListener(TreeEvent.DOUBLE_CLICK_ITEM,onNpctreeEvent);
			
			mapClip.addEventListener(MouseEvent.CLICK,onSmallMap);
			mapClip.addEventListener(MouseEvent.MOUSE_OVER,onMapOver);
			mapClip.addEventListener(MouseEvent.MOUSE_OUT,onMapOut);
//			pageTab.addEventListener(TabEvent.TAB_CLICK,onPage);
			//搜寻
			findbtn.addEventListener(MouseEvent.CLICK,onFindNpc);
//			findinput.inputTxt.addEventListener(TextEvent.TEXT_INPUT,onInputClear);
			findinput.addEventListener(Event.CHANGE,onInputClear);
			
			//勾选框
			allCkb.addEventListener(CheckBox.CHECK_BOX_CLICK,onAllClick);
			shopCkb.addEventListener(CheckBox.CHECK_BOX_CLICK,onShopClick);
			normalCkb.addEventListener(CheckBox.CHECK_BOX_CLICK,onNormalClick);
		}
		
		//=========================小地图鼠标事件==========================
		/**
		 * 点击小地图寻路 
		 * @param e
		 * 
		 */
		private function onSmallMap(e:MouseEvent):void
		{
			//_gamePlay.routeTo(e.localX*_scale,e.localY*_scale);
		}
		
		/**
		 * 鼠标经过，添加事件 
		 * @param event
		 * 
		 */
		private function onMapOver(event:MouseEvent):void
		{
			mapClip.addEventListener(Event.ENTER_FRAME, onMouseMove);
			mousePosLab.visible = true;
		}
		
		/**
		 * 鼠标离开 
		 * @param event
		 * 
		 */
		private function onMapOut(event:MouseEvent):void
		{
			mapClip.removeEventListener(Event.ENTER_FRAME, onMouseMove);
			mousePosLab.visible = false;
		}
		
		/**
		 * 小地图鼠标移动,计算坐标
		 * @param event
		 * 
		 */
		private function onMouseMove(event:Event):void
		{
			var posX	:int	=	this.stage.mouseX - GameStage.x - this.x - this.windowBG.x;
			var posY	:int	=	this.stage.mouseY - GameStage.y - this.y - this.windowBG.y;
			mousePosLab.x = posX + 5;
			mousePosLab.y = posY - 10;
			mousePosLab.htmlStrByBorder = (posX - mapClip.x)*_scale + "," + (posY - mapClip.y)*_scale;
		}
		
		//==================勾选框事件============================
		/**
		 * 点击全部 
		 * @param event
		 * 
		 */
		private function onAllClick(event:Event):void
		{
			if(allCkb.selected)
			{
				shopCkb.selected	=	normalCkb.selected	=	true;
				_business.visible	=	_common.visible		=	true;
			}
			else
			{
				shopCkb.selected	=	normalCkb.selected	=	false;
				_business.visible	=	_common.visible		=	false;
			}
		}
		
		/**
		 * 点击商业 
		 * @param event
		 * 
		 */
		private function onShopClick(event:Event):void
		{
			_business.visible	=	shopCkb.selected;
		}
		
		/**
		 * 点击普通 
		 * @param event
		 * 
		 */
		private function onNormalClick(event:Event):void
		{
			_common.visible	=	normalCkb.selected;
		}
		//==================勾选框事件结束============================
		
		/**
		 * 点击搜索 
		 * @param evt
		 * 
		 */
		private function onFindNpc(evt:MouseEvent):void
		{
//			npcTree.selectItemByData((findinput.htmlStr));
			var str	:String	=	findinput.htmlStr;
			if(str == "")
			{
//				this.showFind = false;
				return;
			}
			findTree.clear();
			//查找结果
			findTree.addItem(StaticIni.getSwfLangStr("1000000622")); 
			for(var i:int=0;i<_npcListArr.length;i++)
			{
				if(StringUtil.contains(_npcListArr[i][0],str) > 0)
				{
					findTree.addItem(_npcListArr[i][0],0,-1,[_npcListArr[i][1],_npcListArr[i][2],_npcListArr[i][3]],"",0,"",0xFFFFFF);
				}
			}
			this.showFind = true;
		}
		
		/**
		 * 输入框清零的时候 
		 * @param event
		 * 
		 */
		private function onInputClear(event:Event):void
		{
			//清空隐藏结果
			if(findinput.inputTxt.length == 0)
			{
				this.showFind = false;
			}
		}
		
		/**
		 * 是否显示搜索结果 
		 * 
		 */
		public function set showFind(val:Boolean):void
		{
			if(_showFind == val)
			{
				return;
			}
			_showFind	=	val;
			if(_showFind)
			{
				npcTree.visible		=	false;
				findTree.visible	=	true;
			}
			else
			{
				findTree.visible	=	false;
				npcTree.visible		=	true;
			}
		}
		
		/**
		 * 设置场景id 
		 * @param val
		 * 
		 */
		public function set modelID(val:String):void
		{
			//只有一个场景，不需要清除
			/*npcTree.clear();
			//清除npc
			for(var i:int=0;i<_panelArr.length;i++)
			{
				var sprite:Sprite=_panelArr[i] as Sprite;
				while(sprite.numChildren)
				{
					sprite.removeChild(sprite.getChildAt(0));	
				}
				
			}
			npcTree.addItem("NPC");*/
			
			//换场景，clipFrame的边框需要清楚，以待在新场景中重新描绘
			if(_clipFrame)
			{
				_clipFrame.graphics.clear();
				_clipFrame = null;
			}
			
			mapClip.source=ResConfig.minMapPath+val+".jpg";
			val = "Min_" + val;
			_scale=int(StaticIni.getIniVar(String(val),"Scale"));
			
			addNpc(StaticIni.getIniVar(String(val),"CommonNPC"),_common,"txt_color_nn","nnNPC",NORMALNPC);
			addNpc(StaticIni.getIniVar(String(val),"CommercialNPC"),_business,"txt_color_tn","dnNPC",SHOPNPC);
//			addNpc(StaticIni.getIniVar(String(val),"TransportNPC"),_transmit,"txt_color_trn","mnNPC");
//			addNpc(StaticIni.getIniVar(String(val),"TaskNPC"),_task,"txt_color_tan","tanNPC");
//			addNpc(StaticIni.getIniVar(String(val),"ActivityNPC"),_activity,"txt_color_mn","tnNPC");
//			addNpc(StaticIni.getIniVar(String(val),"GetDoubelNPC"),_obtain,"txt_color_dn","trnNPC");
		}
		
		/**
		 * 添加地图npc 
		 * @param str
		 * @param bg
		 * @param color
		 * @param npcStr
		 * 
		 */
		private function addNpc(str:String,bg:Sprite,color:String="",npcStr:String="",parent:int=1):void
		{
			if(str==null||StringUtil.trim(str)=="")
			{
				return;
			}
			var npcArr:Array=str.split(";");
			for(var i:int=0;i<npcArr.length;i++)
			{	
				var npcName:Label=new Label();
				var nameNpc:String=StaticIni.getSwfLangStr(npcArr[i]);
				var npcMc:Sprite=ResManager.newResClass(npcStr) as Sprite;
				
				npcName.htmlStrByBorder=StaticIni.getSwfLangStrVar(color,[nameNpc]);
				var npcX:int=int(StaticIni.getIniVar(npcArr[i],"SiteX"))/_scale-npcName.width/2;
				var npcY:int=int(StaticIni.getIniVar(npcArr[i],"SiteY"))/_scale-npcName.height/2;
				npcMc.x=int(StaticIni.getIniVar(npcArr[i],"SiteX"))/_scale;
				npcMc.y=npcY;
				npcName.x=npcX;
				npcName.y=npcY;
				bg.addChild(npcName);
				bg.addChild(npcMc);
				npcTree.addItem(StaticIni.getSwfLangStr(npcArr[i]),parent,-1,[int(StaticIni.getIniVar(npcArr[i],"SiteX")),int(StaticIni.getIniVar(npcArr[i],"SiteY")),npcArr[i]],"",0,"",0xFFFFFF);
//				npcTree.addItem(StaticIni.getSwfLangStr(npcArr[i]),0,-1,[npcArr[i]]);
				_npcListArr.push([StaticIni.getSwfLangStr(npcArr[i]),int(StaticIni.getIniVar(npcArr[i],"SiteX")),int(StaticIni.getIniVar(npcArr[i],"SiteY")),npcArr[i]]);
			}
		}
		
		/**
		 * 双击一个NPC名字
		 * @param e
		 */
		private function onNpctreeEvent(e:TreeEvent):void
		{
			/*_gamePlay.routeTo(e.item.data[0],e.item.data[1]);
			model.sendSceneEvent(SceneEvent.CLOSETONPC,[e.item.data[2]]);*/
		}
		
		/**
		 * 目标pos 
		 * @param value
		 * 
		 */
		public function targetPos(value:Point):void
		{
			_movemc.x=mapClip.x+value.x/_scale-_movemc.width/2;
			_movemc.y=mapClip.y+value.y/_scale-_movemc.height/2;
			if(_endPoint.x == value.x && _endPoint.y== value.y)
			{
				drowline.graphics.clear();
			}
			else
			{
				//实时更新线路，
				/*drowline.graphics.clear();
				drowline.graphics.lineStyle(3,0xE64E27,1);
				//获取路径
				var route	:Array = ObjectMove.getRoute(value.x, value.y, _endPoint.x, _endPoint.y, GameStage.sceneLayer.wall);
				var statline:Point=new Point();
				statline.x=value.x;
				statline.y=value.y;
				var endline	:Point=new Point();
				for each(var point:Array in route)
				{
					endline.x=point[0];
					endline.y=point[1];	
					drawDashedLine(statline.x/_scale,statline.y/_scale,endline.x/_scale,endline.y/_scale,5,5);
					statline.x=endline.x;
					statline.y=endline.y;
				}
				drowline.graphics.endFill();*/
			}
		}
		
		/**
		 * 绘制 
		 * @param array
		 * 
		 */
		public function draw(array:Array):void
		{
			/*drowline.graphics.clear();
			var statline:Point=new Point();
			statline.x=_gamePlay.x;
			statline.y=_gamePlay.y;
			var endline:Point=new Point();
			_endPoint = endline;
			drowline.graphics.lineStyle(3,0xE64E27,1);
			for each(var point:Array in array)
			{
				endline.x=point[0];
				endline.y=point[1];	
				drawDashedLine(statline.x/_scale,statline.y/_scale,endline.x/_scale,endline.y/_scale,5,5);
				statline.x=endline.x;
				statline.y=endline.y;
			}
			drowline.graphics.endFill();*/
		}
		
		/**
		 *  绘制寻路路径
		 * @param beginX
		 * @param beginY
		 * @param endX
		 * @param endY
		 * @param width
		 * @param grap
		 * 
		 */
		private function drawDashedLine(beginX:int,beginY:int,endX:int,endY:int, width:Number, grap:Number):void
		{
			if (!graphics || !beginX|| !beginY || !endX || !endY || width <= 0 || grap <= 0) return;
			var Ox:Number = beginX;
			var Oy:Number =beginY;
			var radian:Number = Math.atan2(endY - Oy, endX - Ox);
			var beginPoint:Point=new Point(beginX,beginY);
			var endPoint:Point=new Point(endX,endY);
			var totalLen:Number = Point.distance(beginPoint, endPoint);
			var currLen:Number = 0;
			var x:Number, y:Number;
			while (currLen <= totalLen)
			{
				x = Ox + Math.cos(radian) * currLen;
				y = Oy +Math.sin(radian) * currLen;
				drowline.graphics.moveTo(x, y);
				currLen += width;
				
				if (currLen > totalLen)
				{
					currLen = totalLen;
				}
				x = Ox + Math.cos(radian) * currLen;
				y = Oy +Math.sin(radian) * currLen;
				drowline.graphics.lineTo(x, y);
				currLen += grap;
			}
		}
		
		/**
		 * 加载地图 
		 * @param val
		 * 
		 */
		private function onLoaded(val:DisplayObject):void
		{
			_clipFrame = new Shape();
			_clipFrame.graphics.lineStyle(1,0x99CC00,1);
			this.windowBG.addChild(_clipFrame);
			this.windowBG.addChild(mapClip);
			this.windowBG.addChild(_business);
//			this.windowBG.addChild(_transmit);
			this.windowBG.addChild(_common);
//			this.windowBG.addChild(_task);
//			this.windowBG.addChild(_activity);
//			this.windowBG.addChild(_obtain);
			this.windowBG.addChild(mousePosLab);
			mousePosLab.visible = false;
			
			this.windowBG.width=mapClip.width + 2*windowBG.offsetX + 235;
			this.windowBG.height=mapClip.height + 2*windowBG.offsetY + 70;
			this.windowBG._closeBtn.x=this.windowBG._bgSpace.width-2*windowBG.offsetX-this.windowBG._closeBtn.width;
			bg_mc2.y=40;
			bg_mc2.width=mapClip.width+20;
			bg_mc2.height=mapClip.height+20;
			
			mapClip.x=bg_mc2.x+10;
			mapClip.y=bg_mc2.y+10;
			_clipFrame.graphics.drawRect(mapClip.x-1,mapClip.y-1,mapClip.width+2,mapClip.height+2);
			
			_business.y=_common.y=mapClip.y;
			_business.x=_common.x=mapClip.x;
			
			bg_mc3.height=bg_mc2.height-50;
			npcTree.reHeight=findTree.reHeight=bg_mc3.height-25;
			var numX:int=bg_mc2.x+bg_mc2.width+10;
			findinput.x=numX;
			findbtn.x=numX+findinput.width;
			npcTree.x=findTree.x=numX+5;
			bg_mc3.x=numX;
			this.windowBG.addChild(drowline);
			this.windowBG.addChild(_movemc);
			drowline.x=mapClip.x;
			drowline.y=mapClip.y;
			drowline.graphics.clear();
			/*_movemc.x=mapClip.x+_gamePlay.x/_scale-_movemc.width/2;
			_movemc.y=mapClip.y+_gamePlay.y/_scale-_movemc.height/2;*/
			
			//定位ui位置
			this.x	=	(GameStage.stageWidth-windowBG.width-GameStage.x*2)/2;
			this.y	=	(GameStage.stageHeight-windowBG.height-GameStage.y*2)/2;
			show();
		}
		
		override public function show(space:String="middle", onshow:Function=null):void
		{
			//初始化设置地图
			if(!_initMap)
			{
				this.modelID = String(model.scene.Model);
				_initMap	=	true;
				return;
			}
			//默认打开全选
			allCkb.selected	=	shopCkb.selected	=	normalCkb.selected	=	true;
			_business.visible	=	_common.visible		=	true;
			//清除路径
//			drowline.graphics.clear();
			super.show(space,onshow)
		}
	}
}